Android 應用程式有多種儲存資料的方式,包括內部和外部儲存空間,像 Room 和 Preferences Datastore。那用Room之前來覆習一下 SQL.
關聯式資料庫的重要概念
關聯式資料庫 (Relational Database) 是現代應用程式中儲存和管理資料的基礎。它以表格的形式組織資料,並通過鍵來建立表之間的關係。
data class Student(
id: Int,
name: String,
major: String,
gpa: Double
)
在 Android Studio 中,依序點選「View」>「Tool Windows」>「App Inspection」。
SELECT 陳述式是 SQL 語言中用來查詢資料庫中資料的基礎指令。透過它,我們可以從一個或多個表格中選取符合特定條件的資料,並以我們想要的方式呈現結果。
SQL
SELECT column1, column2, ...
FROM table_name
WHERE condition;
例如:
SELECT * FROM email;
SELECT subject FROM email;
SELECT subject, sender FROM email;
匯總函數: 用來對一組值進行計算,常見的匯總函數包括:
SQL
-- 計算產品表中不同類型的產品數量
SELECT COUNT(DISTINCT product_type) FROM products;
-- 計算訂單總金額
SELECT SUM(total_price) FROM orders;
-- 找出客戶購買金額最高的訂單
SELECT MAX(total_price) FROM orders;
例如:
SELECT COUNT(*) FROM email;
SELECT MAX(received) FROM email;
SELECT sender FROM email;
SELECT DISTINCT sender FROM email;
SELECT COUNT(DISTINCT sender) FROM email;
WHERE 子句用來指定查詢條件,篩選出符合條件的資料。
SQL
-- 查詢價格大於 100 的產品
SELECT * FROM products WHERE price > 100;
-- 查詢訂單日期在 2023 年的訂單
SELECT * FROM orders WHERE order_date BETWEEN '2023-01-01' AND '2023-12-31';
例如:
SELECT * FROM email
WHERE folder = 'inbox';
SELECT * FROM email
WHERE folder = 'inbox' AND read = false;
SELECT * FROM email
WHERE folder = 'important' OR starred = true;
SELECT COUNT(*) FROM email
WHERE subject LIKE '%fool%';
SELECT * FROM email
WHERE subject LIKE '%fool';
SELECT DISTINCT sender FROM email
WHERE sender LIKE 'h%';
SQL
-- 查詢每個客戶的訂單總金額,並按總金額降序排列
SELECT customer_id, SUM(total_price) AS total_spent
FROM orders
GROUP BY customer_id
ORDER BY total_spent DESC
LIMIT 10;
例如:
SELECT folder, COUNT(*) FROM email
GROUP BY folder;
SELECT * FROM email
ORDER BY received DESC;
SELECT * FROM email
WHERE subject LIKE '%fool%'
ORDER BY received ASC;
SELECT * FROM email
WHERE folder = 'inbox'
ORDER BY received DESC
LIMIT 10;
SELECT * FROM email
WHERE folder = 'inbox'
ORDER BY received DESC
LIMIT 10 OFFSET 10;
SQL
-- 插入一條新的客戶記錄
INSERT INTO customers (name, email) VALUES ('John Doe', 'johndoe@example.com');
-- 更新客戶的電子郵件地址
UPDATE customers SET email = 'new_email@example.com' WHERE id = 1;
-- 刪除 id 為 2 的客戶
DELETE FROM customers WHERE id = 2;
例如:
INSERT INTO email
VALUES (
NULL, 'Lorem ipsum dolor sit amet', 'sender@example.com', 'inbox', false, false, CURRENT_TIMESTAMP
);
SELECT * FROM email
WHERE sender = 'sender@example.com';
UPDATE email
SET read = true
WHERE id = 44;
SELECT read FROM email
WHERE id = 44;
DELETE FROM email
WHERE id = 44;
SELECT * FROM email
WHERE id = 44;